<?php
//$js = <<<EOP
//$.afterAjaxUpdate = function(id, data){
//    $.each($('#'+id).find('.table'), function(){
//        //clean zombie event before reinit
//        $(document).off('click.yiiGridView', '#' + $(this).attr('id') + ' .select-on-check');
//        $(document).off('click.yiiGridView', '#' + $(this).attr('id') + ' .items > tbody > tr');
//
//        jQuery('#'+$(this).attr('id')).yiiGridView({
//            'ajaxUpdate':[$(this).attr('id')],
//            'ajaxVar':'subproduct',
//            'pagerClass':'pager',
//            'loadingClass':'grid-view-loading',
//            'filterClass':'filters',
//            'tableClass':'items',
//            'selectableRows':2,
//            'enableHistory':false,
//            'updateSelector':'{page}, {sort}',
//            'pageVar':'SubProduct_page'
//        });
//    });
//    //update summary data
//    $('#grid-product .summary:first').remove();
//    $('#grid-product').prepend($(data).find('.summary'));
//    $('#ajax-loading').hide();
//    $.restoreProductState();
//};
//EOP;
//cs()->registerScript(__CLASS__.'#InitGridViewAfterAjax', $js);
?>
<h1>Products</h1>

<?php $this->renderPartial('_export_form'); ?>

<div class="btn-group">
    <a class="btn" href="#"><i class="icon-wrench"></i> Actions</a>
    <a class="btn dropdown-toggle" data-toggle="dropdown" href="#"><span class="caret"></span></a>
    <ul class="dropdown-menu">
        <li><a href="<?php echo $this->createUrl('create'); ?>" class="xtarget-detail"><i class="icon-file"></i> Create
                New Product</a></li>
        <li><a href="<?php echo $this->createUrl('/Shop/admin/product/delete'); ?>"
               class="lnk-delete-products-multiply"><i class="icon-trash"></i> Delete selected item(s)</a></li>
        <li><a href="#" class="lnk-set-on-sale-products-multiply"><i class="icon-pencil"></i> Set On Sale</a></li>
        <li><a href="#" class="lnk-export-product export-to-excel"><i class="icon-share"></i> Export to Excel</a></li>
<!--        <li class="divider"></li>-->
<!--        <li><a href="#" class="expand-all"><i class="i"></i> Expand all</a></li>-->
<!--        <li><a href="#" class="collapse-all"><i class="i"></i> Collapse all</a></li>-->
    </ul>
</div>
<div class="grid-view table table-hover" id="grid-product">
    <table class="product-items">
        <thead>
        <tr>
            <th width="10"><?php echo CHtml::checkBox('check_all', false, array('class' => 'product-check-all')); ?></th>
            <th>Name</th>
            <th width="200">Custom URL</th>
            <th width="160">Category</th>
            <th width="100">Gallery</th>
            <th width="100">Default SKU</th>
            <th width="50" style="text-align: center">Status</th>
            <th width="50" class="actions-header">&nbsp;</th>
        </tr>
        <tr class="product-filters">
            <td width="10"></td>
            <td><input type="text" name="name" placeholder="Product name" maxlength="255"></td>
            <td><input type="text" name="custom_url" placeholder="Custom Url" maxlength="255"></td>
            <td width="160">
                <?php echo CHtml::dropDownList('category', '', $categories, array('prompt' => '---', 'encode' => false, 'class' => 'span2')); ?>
            </td>
            <td width="100"></td>
            <td width="100"><input type="text" name="default_sku" placeholder="SKU" maxlength="255"></td>
            <td width="100" style="text-align: center">
                <select name="status" class="input-small">
                    <option value="">---</option>
                    <option value="1">Show</option>
                    <option value="0">Hide</option>
                </select>
            </td>
            <td width="50" class="actions-header">&nbsp;</td>
        </tr>
        </thead>
    </table>
    <?php $this->widget('zii.widgets.CListView', array(
        'id' => 'product-list',
        'dataProvider' => $dataProvider,
        'itemView' => '_view',
        'itemsTagName' => 'ul',
        'template' => "{items}\n{pager}\n{summary}",
//        'afterAjaxUpdate'=>"$.afterAjaxUpdate",
    )); ?>
</div>
<div id="preview-options-modal" class="modal hide fade">
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h3>Choose Url to preview</h3>
    </div>
    <div class="modal-body">
        <label>Page:</label>
        <select class="preview-option-page"></select>
        <label>Url:</label>
        <select class="preview-option-url"></select>
    </div>
    <div class="modal-footer">
        <a href="#" class="btn" data-dismiss="modal" aria-hidden="true">Close</a>
        <a href="#" class="btn btn-primary" target="_blank">Preview</a>
    </div>
</div>
<?php
//$js = <<<EOP
//$('body').on('subproduct.show',function(event, el){
//    var id = $(el).find('.table').attr('id');
//    $('#'+id).hide();
//    $('#ajax-loading').show();
//    $.fn.yiiGridView.update(id);
//});
//EOP;
//cs()->registerScript(__CLASS__.'#UpdateSubproduct', $js);

$script = "
//var product_state = $.cookie('product_state');
//if (product_state === null)
//    product_state = {};
//else
//    product_state = JSON.parse(product_state);
//
//function updateTreeState(id, isShow){
//    if (isShow != undefined && isShow == true)
//    {
//        product_state[id] = isShow;
//        if ($(this).hasClass('loaded') == false)
//        {
//            $(this).addClass('loaded');
//            $('body').trigger('subproduct.show', [this]);
//        }
//    }
//    else
//    {
//        //remove
//        if (product_state[id] != undefined)
//            delete product_state[id];
//    }
//    $.cookie('product_state',JSON.stringify(product_state));
//}

////restore previous state
//$.restoreProductState = function(){
//    $.each(product_state, function(id, isShow){
//        if ($('#'+id).size())
//        {
//            $('#'+id).addClass('expland');
//            updateTreeState.call($('#'+id), id, true);
//        }
//    });
//}
//$.restoreProductState();

$('body').delegate('.toggle', 'click', function(){
//    $(this).closest('li').toggleClass('expland');
//    //save current state of node to cookie
//    var li_el = $(this).closest('li');
//    updateTreeState.call(li_el, li_el.attr('id'), li_el.hasClass('expland'))
//    return false;
    var productId = $(this).attr('id');
    var productName = $(this).attr('name');
    var href = '" . url('/Shop/admin/product/subproductsAdmin') . "' + '&productId=' + productId + '&productName=' + productName;
    parent.$.fancybox({
            type: 'iframe',
            href: href,
            width: '100%',
            height: '100%',
            showCloseButton: true,
            hideOnOverlayClick: false,
            autoScale: false,
            titleShow: false,
            'onComplete' : function() {
                parent.$('#fancybox-overlay').css({'z-index':'100002'});
                parent.$('#fancybox-wrap').css({'z-index':'100003','top':'40px','left':'40px'});
                parent.$('#fancybox-frame').load(function() {
                });
            },
            'onClosed': function() {
//                window.location.reload('".url('/Shop/admin/product')."');
                  if(parent.refresh == 1){
                     $.fn.yiiListView.update('product-list');
                     parent.refresh = 0;
                  }
            }
    });
});

//$('body').on('click','.btn-group .expand-all',function(){
//    $.each($('.product-items .toggle'),function(){
//        if ($(this).closest('li').hasClass('expland') == false)
//            $(this).trigger('click');
//    });
//});
//$('body').on('click','.btn-group .collapse-all',function(){
//    $.each($('.product-items .toggle'),function(){
//        if ($(this).closest('li').hasClass('expland'))
//            $(this).trigger('click');
//    });
//});
";
cs()->registerScript(__CLASS__ . '#Toggle', $script);

$js = <<<EOP
$('.list-view .summary').insertBefore('.product-items:first');
EOP;

cs()->registerScript(__CLASS__ . '#FixSummaryPos', $js);

$js = <<<EOP
var eventType;
$(document).on('change keydown', '.product-filters input,.product-filters select', function (event) {
    if (event.type === 'keydown') {
        if( event.keyCode !== 13) {
            return; // only react to enter key
        } else {
            eventType = 'keydown';
        }
    } else {
        // prevent processing for both keydown and change events
        if (eventType === 'keydown') {
            eventType = '';
            return;
        }
    }
    var data = $('.product-filters input,.product-filters select').serialize();
    data += '&Product_page=1';
    $.fn.yiiListView.update('product-list', {data: data});
});
EOP;

cs()->registerScript(__CLASS__ . '#FilterProduct', $js);

$js = <<<EOP
$('body').on('click', '.product-status-column > a', function(){
    var href = $(this).attr('href');
    var data = $.deparam.querystring(href);
    $.post(href, data, function(){
        $.fn.yiiListView.update('product-list');
    });
    return false;
});
EOP;

cs()->registerScript(__CLASS__ . '#ChangeProductStatus', $js);

$js = <<<EOP
$('body').on('click', '.product-actions-column > .delete', function(){
    if (!confirm('Are you sure you want to delete this product?')) return false;
    var href = $(this).attr('href');
    var data = $.deparam.querystring(href);
    $.post(href, data, function(data){
        data = $.parseJSON(data);
        if (data != null)
        {
            if (data['error'] == undefined)
                $.fn.yiiListView.update('product-list');

            alert(data['msg']);
        }
    });
    return false;
});
EOP;

cs()->registerScript(__CLASS__ . '#ProductDelete', $js);

cs()->registerCoreScript('cookie');
cs()->registerCoreScript('bbq');

$js = <<<EOP
$('body').on('click','.product-check-all',function(){
    var isChecked = $(this).is(':checked');
    $('.product-checkbox-column .select-on-check').attr('checked', isChecked);
});
EOP;
cs()->registerScript(__CLASS__ . '#CheckAllProduct', $js);

$js = <<<EOP
$('body').on('click','.lnk-delete-products-multiply',function(){
    var href = $(this).attr('href'), id = [];

    $.each($('.product-checkbox-column .select-on-check:checked'),function(){
        id.push($(this).val());
    });

    if (id.length <= 0)
    {
        $('.btn-group .dropdown-toggle').dropdown('toggle');
        alert('You must choose least one product');
        return false;
    }

    if (!confirm('Are you sure you want to delete this products?'))
    {
        $('.btn-group .dropdown-toggle').dropdown('toggle');
        return false;
    }
    id = id.join(',');
    href = $.param.querystring(href, {id:id});
    $.post(href, function(data){
        data = $.parseJSON(data);
        if (data != null)
        {
            //update product list
            if (data['error'] == undefined)
                $.fn.yiiListView.update('product-list');

            alert(data['msg']);
        }
    });
    $('.btn-group .dropdown-toggle').dropdown('toggle');
    return false;
});
EOP;

cs()->registerScript(__CLASS__ . '#DeleteMultiProduct', $js);

$js_export = <<<EOP
$('a.lnk-export-product').click(function(){
    if ($(this).hasClass('export-to-excel'))
    {
        $('#export-file-extension').val('excel');
    }
    else
    {
        $('#export-file-extension').val('pdf');
    }
    // get filters
    $('#grid-product table tr.product-filters input, #grid-product table tr.product-filters select').each(function(){
        var control_name = $(this).attr('name');
        var filter_value = $(this).val();
        var filter_id = 'filter_'+control_name;
        $('#form-export-product #'+filter_id).val(filter_value);
    });
    $('#form-export-product').submit();
});
EOP;

cs()->registerScript(__CLASS__ . '#ExportProduct', $js_export);
?>
<script>
    //Set on-sale multiple products
    $('a.lnk-set-on-sale-products-multiply').live('click', function () {
        var url = '<?php echo url('/Shop/admin/product/setOnSale'); ?>';
        var product_ids = new Array();
        $.each($('.product-checkbox-column .select-on-check:checked'), function () {
            product_ids.push($(this).val());
        });

        if (product_ids.length <= 0) {
            $('.btn-group .dropdown-toggle').dropdown('toggle');
            alert('Please select at least an item !');
            return false;
        }

        url = url + '&id=' + product_ids.join(',');
        parent.$.fancybox({
            type: 'iframe',
            href: url,
            width: '40%',
            height: '45%',
            showCloseButton: true,
            hideOnOverlayClick: false,
            autoScale: false,
            titleShow: false,
            'onComplete': function () {
                parent.$('#fancybox-overlay').css({'z-index': '100002'});
                parent.$('#fancybox-wrap').css({'z-index': '100003', 'top': '40px', 'left': '40px'});
                parent.$('#fancybox-frame').load(function () {
                });
            }
        });
    });
</script>